package insight.springia5.chapter06.data;

import insight.springia5.chapter06.domain.Taco;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * 与 data-rest 配合使用的 Controller
 * 使用 @RepositoryRestController 是路径与 data-rest 相同
 * 不过不包含 @ResponseBody
 * 注意： 要使用 @RepositoryRestController 必须手动配置 base-path
 * 
 * 虽然 RepositoryRestController 会帮你携带 base-path
 * 但是在配置自定义超链接的时候 就不会帮你携带... 到头来还是需要自己配一下路径
 * 
 * @author insight 
 * @since 2021/7/19
 */
@RepositoryRestController
@RequestMapping("/api/tacos")
public class RecentController {
    private TacoRepository tacoRepository;

    @Autowired
    public RecentController(TacoRepository tacoRepository) {
        this.tacoRepository = tacoRepository;
    }

    @GetMapping(path="/recent", produces="application/hal+json")
    public ResponseEntity<List<Taco>> recentTacos() {
        PageRequest page = PageRequest.of(
                0, 12, Sort.by("createdAt").descending());
        List<Taco> tacos = tacoRepository.findAll(page).getContent();
        return new ResponseEntity<>(tacos, HttpStatus.OK);
    }
}